﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;

using System.Xml.Serialization;

namespace DesktopBroadcast
{
    public enum ImageType
    {
        Bmp,
        Emf, Exif, Gif, Icon, Jpeg, MemoryBmp, Png, Tiff, Wmf
    }
    public class ConfigItem
    {
        public ConfigItem()
        {
            BroadcastAddress = "234.0.0.1";
            BroadcastPort = 7788;
            Interval = 250;
            ScreenFormat = ImageType.Jpeg;
            Compress = false;
        }

        [Category("数据"), Description("广播地址")]
        public string BroadcastAddress { get; set; }
        [Category("数据"), Description("端口")]
        public int BroadcastPort { get; set; }
        [Category("数据"), Description("屏幕发送周期（ms）")]
        public int Interval { get; set; }
        [Category("数据"), Description("屏幕图像格式")]
        public ImageType ScreenFormat { get; set; }
        [Category("数据"), Description("是否压缩图像")]
        public bool Compress { get; set; }

        public static ImageType TransType(ImageType type)
        {
            switch (type)
            {
                case ImageType.Bmp: return ImageType.Bmp;
                case ImageType.Emf: return ImageType.Emf;
                case ImageType.Exif: return ImageType.Exif;
                case ImageType.Gif: return ImageType.Gif;
                case ImageType.Icon: return ImageType.Icon;
                case ImageType.Jpeg: return ImageType.Jpeg;
                case ImageType.MemoryBmp: return ImageType.MemoryBmp;
                case ImageType.Png: return ImageType.Png;
                case ImageType.Tiff: return ImageType.Tiff;
                case ImageType.Wmf: return ImageType.Wmf;
                default: return ImageType.Jpeg;
            }
        }

        public static void Persistent(ConfigItem data)
        {
            using (FileStream fs = new FileStream("ServerConfig.xml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
            {
                XmlSerializer xs = new XmlSerializer(typeof(ConfigItem));
                xs.Serialize(fs, data);
            }
        }

        public static ConfigItem GetConfig()
        {
            ConfigItem config = new ConfigItem();
            if (!File.Exists("ServerConfig.xml"))
                return config;
            using (FileStream fs = new FileStream("ServerConfig.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                try
                {
                    XmlSerializer xs = new XmlSerializer(typeof(ConfigItem));
                    var temp = xs.Deserialize(fs) as ConfigItem;
                    if (temp != null)
                        config = temp;
                }
                catch
                {
                    return config;
                }
            }
            return config;
        }
    }
}
